<template>
  <div class="component-upload-image">
    <el-upload :action="uploadImgUrl" ref="uploadRef" list-type="picture" :on-error="handleUploadError"
      :on-exceed="handleExceed" name="file" :before-upload="handleBeforeUpload" :show-file-list="false"
      :headers="headers" :file-list="fileList" :on-success="handleUploadSuccess" :on-change="handleChangePic"
      :auto-upload="false" :on-remove="handleRemove">
      <p>上传图片</p>
    </el-upload>

  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import { delOss } from "@/api/system/oss";

const props = defineProps({
  modelValue: [String, Object, Array],

  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ['jpg', 'jpeg', 'png'],
  },
  width: {
    type: String,
    default: () => '690'
  },
  height: {
    type: String,
    default: () => '390'
  }

});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload"); // 上传的图片服务器地址
const headers = ref({ Authorization: "Bearer " + getToken(), 'tenant-host-name': window.location.hostname });
const fileList = ref([]);
const showBtnDealImg = ref(true)
const noneBtnImg = ref(false)
const imgUrl = ref('')//上传图片后地址合集
const failure = ref(false)
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
watch(() => props.modelValue, val => {
  // console.log('props.modelValue', props.modelValue)
  if (val) {
    let list;
    if (list == Array.isArray(val)) {
      fileList.value = list.map(item => {
        // 此处name使用ossId 防止删除出现重名
        item = { name: item.ossId, url: item.url, ossId: item.ossId, };
        return item;
      });

    } else {

      fileList.value = props.modelValue.split(",").map((item, i) => {
        item = { name: 'pic' + getRandomString(4), url: props.modelValue, ossId: 'ossId' + getRandomString(2) };
        // console.log('fileList.value======', item)
        return item;
      })

    }

  } else {
    fileList.value = [];
    return [];
  }
}, { deep: true, immediate: true });

/**
 * 随机生成字符串
 * @param len 指定生成字符串长度
 */
function getRandomString(len) {
  let _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789',
    min = 0,
    max = _charStr.length - 1,
    _str = '';                    //定义随机字符串 变量
  //判断是否指定长度，否则默认长度为15
  len = len || 15;
  //循环生成字符串
  for (var i = 0, index; i < len; i++) {
    index = (function (randomIndexFunc, i) {
      return randomIndexFunc(min, max, i, randomIndexFunc);
    })(function (min, max, i, _self) {
      let indexTemp = Math.floor(Math.random() * (max - min + 1) + min),
        numStart = _charStr.length - 10;
      if (i == 0 && indexTemp >= numStart) {
        indexTemp = _self(min, max, i, _self);
      }
      return indexTemp;
    }, i);
    _str += _charStr[index];
  }
  return _str;
}

// 删除图片
function handleRemove(file, files) {
  console.log('删除图片', file, 'files==', files)
  const findex = fileList.value.map(f => f.name).indexOf(file.name);
  if (findex > -1) {
    let ossId = fileList.value[findex].ossId;
    delOss(ossId);
    emit("update:modelValue", fileList.value);

  }
  proxy.$emit('RemoveSuccess', files)
}

// 上传成功回调
/*
 *@description:
  imgLength: 用来判断上传位置,当上传到最后一张时再抛出回调
  因为按照目前写法每次上传成功都会产生一次handleUploadSuccess,
  所以只在最后一次抛出父组件需要的回调
  resList: 抛出的返回值
  fileList: 当前组件绑定的文件数组
 *@date: 2022-07-12 14:51:08
*/
const imgLength = ref(0)
const resList = ref([])
function handleUploadSuccess(res) {
  proxy.$refs.uploadRef.clearFiles()
  if (res.code == 200) {
    resList.value.push(res.data)
    imgLength.value += 1
    if (imgLength.value < fileList.value.length) {
      return
    } else {
      proxy.$emit('UploadSuccess', resList.value)
      // proxy.$modal.closeLoading();
      resList.value = []
      imgLength.value = 0
    }
  } else {
    proxy.$modal.msgError(res.msg);
    proxy.$modal.closeLoading();
  }
}

// 上传前loading加载
function handleBeforeUpload(file) {
  console.log(file)
  imgchecked(file);
}
function handleChangePic(file) {
  // console.log('上传的', file)
  // console.log('正在上传的', fileList.value)
  let isLt10M = file.size / 1024 / 1024 < 5
  if (!isLt10M) {
    proxy.$modal.msgError("上传文件大小不能超过 5MB!");
    return false;
  }

  let type = file.raw.type
  let isType =
    type === "image/png" ||
    type === "image/jpg" ||
    type === "image/jpeg";
  if (!isType) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
    );
    return false;
  };
  if (isType && isLt10M) {
    if (fileList.value.length > 1) {
      fileList.value = [fileList.value[fileList.value.length - 1]]
      proxy.$nextTick(() => {
        // 主动去调用提交接口
        proxy.$refs['uploadRef'].submit();
      })

      // 若文件只有一个，直接上传
    } else {
      proxy.$refs['uploadRef'].submit();

    }

  } else {
    return false;
  }


}
//判断尺寸方法
function imgchecked(file) {
  // 定义 filereader对象
  let reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = e => {
    const img = e.target.result;
    const image = new Image()
    image.src = img
    image.onload = _ => {
      let width = image.width
      let height = image.height
      //     console.log('rrrrr22222', width)
      // 然后就可以做需要的操作了
      if (width != props.width && height != props.height) {
        proxy.$modal.msgError('推荐上传的图片尺寸为' + props.width + '*' + props.height);
      }
    }
  }
}

// 文件个数超出
function handleExceed() {
  //proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);

}

// 上传失败
function handleUploadError(res) {
  proxy.$modal.msgError("上传图片失败");
  proxy.$modal.closeLoading();
  failure.value = true;
  proxy.$emit('disable', failure.value)
}
//
function submitUpload() {
  if (fileList.value && fileList.value.length == 0) {
    proxy.$emit('unFile')
  }
  proxy.$refs['uploadRef'].submit();
  proxy.$modal.closeLoading();
}
// 预览
function handlePictureCardPreview(file) {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}

defineExpose({
  submitUpload
});
</script>
<style lang="scss" >
.hide .el-upload--picture-card {
  display: none;
}
</style>
